<template>
  <div id="questionnaireFieldDAS">
    <configCompositionTwoWindowStyle>
      <template slot="card">
        <div class="searchWrap">
          <div class="search">
            <div class='fl'>
              <span class="icon-text" @click.stop="addQues" v-if="tempData.status !== 'disable'"><i class="el-icon-plus"></i>{{$t('public.add')}}</span>
              <span class="icon-text" @click.stop="refresh"><i class="iconfont icon-shuaxin"></i>{{$t('public.refresh')}}</span>
            </div>
          </div>
        </div>
        <div class="diy-table">
          <el-table :data="tableData" :highlight-current-row="true" :stripe="true" style="width: 100%" v-loading="tableLoading" size="mini">
            <template v-for="item in tableHeader">
              <el-table-column
                v-if="item.prop !== 'handel'"
                :prop="item.prop"
                :label="item.label">
              </el-table-column>
              <el-table-column
                v-if="item.prop === 'handel'"
                :label="item.label">
                <template scope="scope">
                  <el-button @click="updata(scope.row)" type="text" size="small" :disabled="tempData.status === 'disable'" class="updata">{{$t('public.edit')}}</el-button>
                  <!--<el-button @click="moveUp(scope.row)" v-if="scope.$index !== 0" type="text" size="small" :disabled="tempData.status === 'disable'" class="updata">上移{{scope.index}}</el-button>-->
                  <!--<el-button @click="moveDown(scope.row)" v-if="scope.$index !== (tableData.length - 1)" type="text" size="small" :disabled="tempData.status === 'disable'" class="updata">下移</el-button>-->
                  <!--<el-button @click="moveFirst(scope.row)" v-if="scope.$index !== 0" type="text" size="small" :disabled="tempData.status === 'disable'" class="updata">最前</el-button>-->
                  <!--<el-button @click="moveLast(scope.row)" v-if="scope.$index !== (tableData.length - 1)" type="text" size="small" :disabled="tempData.status === 'disable'" class="updata">最后</el-button>-->
                  <el-button @click="deleteQues(scope.row)" type="text" size="small" :disabled="tempData.status === 'disable'" class="delete">{{$t('public.delete')}}</el-button>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </template>
      <template slot="detail">
        <div class="showDetial" v-if="showRight">
          <div class="showDetialTitle" v-text="isAdd ? $t('configLazyLoad.questionnaireConfig.addQuestion') : $t('configLazyLoad.questionnaireConfig.editQuestion')"></div>
          <el-form ref="form" :model="quesForm" :rules="rules" label-position="left" label-width="100px"  v-loading="isLoadingAddOrEdit">
            <el-form-item :label="$t('configLazyLoad.questionnaireConfig.quesMark')" prop="name">
              <el-input v-model.trim="quesForm.name"></el-input>
            </el-form-item>
            <el-form-item :label="$t('configLazyLoad.questionnaireConfig.quesDesc')">
              <el-input type="textarea" v-model="quesForm.context"></el-input>
              <p class="tips">{{$t('configLazyLoad.questionnaireConfig.quesTip1')}}
                <a href="javascript:;" v-for="item in quesTmpls" @click="insertFieldVariable(item.name)">{{item.name}}</a>
              </p>
            </el-form-item>
            <el-form-item label=" ">
              <el-radio-group v-model.trim="quesForm.isMultiselect" @change="isMultiselectChange">
                <el-radio size="mini" :label="false">{{$t('configLazyLoad.questionnaireConfig.singleChoice')}}</el-radio>
                <el-radio size="mini" :label="true">{{$t('configLazyLoad.questionnaireConfig.multipleChoice')}}</el-radio>
              </el-radio-group>
              <br/>
              <el-radio-group v-model.trim="quesForm.jumpType" size="mini">
                <el-radio size="mini" label="no">{{$t('configLazyLoad.questionnaireConfig.noSkipping')}}</el-radio>
                <el-radio :disabled="quesForm.isMultiselect" size="mini" label="ansJump">{{$t('configLazyLoad.questionnaireConfig.jumpByAnswer')}}</el-radio>
                <el-radio size="mini" label="directJump">{{$t('configLazyLoad.questionnaireConfig.unconditionalJump')}}</el-radio>
              </el-radio-group>
              <questionToolTip style="margin-left: 10px;" :tipContent="$t('configLazyLoad.questionnaireConfig.quesTip5')"></questionToolTip>
              <br/>
              <span v-show="quesForm.jumpType === 'directJump'"  style="font-size: 12px;">{{$t('configLazyLoad.questionnaireConfig.unconditionalJumpTo')}}：</span>
              <el-select v-model.trim="quesForm.next" :placeholder="$t('public.pleasePick')" v-show="quesForm.jumpType === 'directJump'" @change="goNextSelect" style="width: 236px;">
                <el-option
                  v-for="item in tableDataForSelect"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id">
                </el-option>
                <el-option
                  value="end"
                  :label="$t('configLazyLoad.questionnaireConfig.endTheAnswer')">
                </el-option>
              </el-select>
            </el-form-item>
            <div class="show_answer" v-for="(item, index) in quesForm.anws" >
              <div class="show_answer_label">{{$t('configLazyLoad.questionnaireConfig.answer')}}:</div>
              <div class="show_answer_item">
                <el-row>
                  <el-col :span="10">
                    <el-input type="text" v-model.trim="item.answer" :placeholder="$t('public.pleaseInput')"></el-input>
                  </el-col>
                  <el-col :span="2" style="text-align: center" v-show="quesForm.jumpType === 'ansJump'">
                    <span class="label_item">{{$t('configLazyLoad.questionnaireConfig.flowTo')}}</span>
                  </el-col>
                  <el-col :span="10" v-show="quesForm.jumpType === 'ansJump'">
                    <el-select v-model.trim="item.next" :placeholder="$t('public.pleasePick')" @change="goNextSelect">
                      <el-option
                        v-for="item in tableDataForSelect"
                        :key="item._id"
                        :label="item.name"
                        :value="item._id">
                      </el-option>
                      <el-option
                        value="end"
                        :label="$t('configLazyLoad.questionnaireConfig.endTheAnswer')">
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="2" style="text-align: center">
                    <el-button class="edit_del el-icon-minus color" type="text" size="mini" @click.prevent="removeQuesItem(item, index)"></el-button>
                  </el-col>
                </el-row>
              </div>
            </div>
            <el-form-item>
              <el-button type="text" @click.stop="addQuesItem" size="small" class="color el-icon-plus"> {{$t('configLazyLoad.questionnaireConfig.addAnswer')}}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="saveQues" type="primary" class="primary_btn fr">{{$t('public.save')}}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </configCompositionTwoWindowStyle>
  </div>
</template>

<script>
  import Vue from 'vue'
  import questionToolTip from '../../../../ui-modules/questionToolTip/QuestionToolTip.vue'
  import configCompositionTwoWindowStyle from '../../../../ui-modules/config/configCompositionTwoWindowStyle'
//  import { getCache } from '@/utils/m7Utils.js'
  import search from '../../channelConfig/base/search'
  import breadCrumb from '../../channelConfig/base/breadCrumb'
  export default {
    name: 'questionnaireFieldConfig',
    data () {
      return {
        rules: {
          name: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
        },
        agents: [],
        currentPage: 1,    //   当前页
        tableHeader: [
          {prop: 'detial', label: this.$t('configLazyLoad.questionnaireConfig.quesName')},
          {prop: 'handel', label: this.$t('public.operate')}
        ],                        //   自定义 表头
        tableData: [],           //  表格数据
        tableLoading: false,      //   表格  loading
        showRight: false,           //   右侧显示隐藏
        isLoadingAddOrEdit: false,
        quesForm: {
          anws: [],
          isMultiselect: false,
          jumpType: 'no'
        },
        isAdd: false,
        checked: false,
        goNextSelectFlagAns: true,   //  校验跳题 是否是 跳到此题之后的问题
        goNextSelectFlagDir: true,   //  校验跳题 是否是 跳到此题之后的问题
        tempData: {},
        currentAnswId: '',
        quesTmpls: []
      }
    },
    props: {
      tempId: {
        type: String,
        default: ''
      }
    },
    watch: {
      tempId () {
        this.showRight = false
        this.currentPage = 1
        this.search()
      }
    },
    components: {
      configCompositionTwoWindowStyle,
      questionToolTip,
      search,
      breadCrumb
    },
    computed: {
      tableDataForSelect () {
        let currentAnswIdIndex = 0
        if (this.currentAnswId) {
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.currentAnswId === this.tableData[i]._id) {
              currentAnswIdIndex = Number(this.tableData[i].order)
              break
            }
          }
          let arr = []
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].order > currentAnswIdIndex) {
              arr.push(this.tableData[i])
            }
          }
          return arr
        }
      }
    },
    methods: {
      goNextSelect (val) {
        this.goNextSelectFlagAns = true
        this.goNextSelectFlagDir = true
//        let selectIndex = 0
//        let currentAnswIdIndex = 0
//        if (this.currentAnswId) {
//          for (let i = 0; i < this.tableData.length; i++) {
//            if (this.currentAnswId === this.tableData[i]._id) {
//              currentAnswIdIndex = Number(this.tableData[i].order)
//              break
//            }
//          }
//          for (let i = 0; i < this.tableData.length; i++) {
//            if (val === this.tableData[i]._id) {
//              selectIndex = Number(this.tableData[i].order)
//              break
//            }
//          }
//          if (selectIndex <= currentAnswIdIndex) {
//            if (this.quesForm.jumpType === 'ansJump') {
//              this.goNextSelectFlagAns = false
//            } else if (this.quesForm.jumpType === 'directJump') {
//              this.goNextSelectFlagDir = false
//            }
//            this.$message.error('只能选择此题之后的问题进行跳题')
//            return
//          }
//        } else {
//          if (this.quesForm.jumpType === 'ansJump') {
//            this.goNextSelectFlagAns = false
//          } else if (this.quesForm.jumpType === 'directJump') {
//            this.goNextSelectFlagDir = false
//          }
//          this.$message.error('只能选择此题之后的问题进行跳题')
//          return
//        }
      },
      isMultiselectChange () {
        if (this.quesForm.isMultiselect) {
          if (this.quesForm.jumpType === 'ansJump') {
            this.quesForm.jumpType = 'no'
          }
        }
      },
      addQues () { // 添加新的问题模板
        if (this.tempData.status === 'disable') {
          this.$message.error(this.$t('configLazyLoad.questionnaireConfig.theTempDisabled'))
          return
        } // 模板禁用了
        this.isAdd = true
        Vue.delete(this.quesForm, '_id')
        Vue.set(this.quesForm, 'name', '')
        Vue.set(this.quesForm, 'context', '')
        Vue.set(this.quesForm, 'anws', [])
        Vue.set(this.quesForm, 'temp_id', this.tempId)
        Vue.set(this.quesForm, 'isMultiselect', false)
        Vue.set(this.quesForm, 'next', '')
        Vue.set(this.quesForm, 'jumpType', 'no')
        this.resetForm()
        this.quesTmpls = []
        let p1 = this.$store.dispatch('getCache', {type: 'questionnaireField', loadFromServer: true})
        let self = this
        Promise.all([p1]).then(() => {
          let fields = this.$getCache('questionnaireField') || []
          for (let i = 0; i < fields.length; i++) {
            if (fields[i].temp_id === self.tempId) {
              this.quesTmpls.push(fields[i])
            }
          }
          this.isLoadingAddOrEdit = false
        })
        this.currentAnswId = ''
        this.showRight = true
      },
      addQuesItem () { // 新增的问题
        if (this.quesForm.anws) {
          this.quesForm.anws.push({answer: '', next: '', _id: ''})
        }
      },
      removeQuesItem (item, index) { // 移除问题
        if (this.quesForm.anws) {
          this.quesForm.anws.splice(index, 1)
        }
      },
      resetForm () {
        if (this.$refs.form) {
          this.$refs.form.resetFields() // 表单重置
        }
      },
      refresh () { // 刷新
        this.showRight = false
        this.currentPage = 1
        this.search()
      },
      search () {
        this.tableLoading = true
        this.$store.dispatch('getQuestionnaireTempById', {_id: this.tempId}).then(res => {
          if (res.success) {
            this.tempData = res.data
          }
        })
//        this.tempData = getCache('questionnaireTemp', this.tempId)
//        this.$store.dispatch('getCache', {type: 'questionnaireTemp', id: this.tempId}).then((res) => {
//          this.tempData = res
//        })
        this.$store.dispatch('queryQuestionnaireQues', {temp_id: this.tempId}).then((res) => {
          if (res.success) {
            let tableData = []
            res.data.forEach((item, index) => {
              tableData.push({name: item.name, detial: item.name + ':' + item.context, _id: item._id, order: item.order})
            })
            this.tableData = tableData
            this.tableLoading = false
          }
        })
      },
      insertFieldVariable (name) { // 插入模板字段
        this.quesForm.context = this.quesForm.context + '${' + name + '}'
      },
      updata (val) {
        this.isAdd = false
        let id = val._id
        this.currentAnswId = val._id
        this.quesForm = {}
        this.quesTmpls = []
        this.showRight = true
        this.isLoadingAddOrEdit = true
        this.resetForm()
        let p1 = this.$store.dispatch('getQuesById', {_id: id})
        let p2 = this.$store.dispatch('getCache', {type: 'questionnaireField'})
        let self = this
        Promise.all([p1, p2]).then(([res]) => {
          if (res.success) {
            this.quesForm = res.data
            let flag = false
            this.quesForm.anws.forEach(item => {
              flag = false
              this.tableData.forEach(one => {
                if (item.next === one._id) {
                  flag = true
                }
              })
              if (!flag) {
                item.next = 'end'
              }
            })
            let flag2 = false
            this.tableData.forEach(one => {
              if (this.quesForm.next === one._id) {
                flag2 = true
              }
            })
            if (!flag2) {
              this.quesForm.next = 'end'
            }
            if (!this.quesForm.isMultiselect) {
              Vue.set(this.quesForm, 'isMultiselect', false)
            }
            let fields = this.$getCache('questionnaireField') || []
            for (let i = 0; i < fields.length; i++) {
              if (fields[i].temp_id === self.tempId) {
                this.quesTmpls.push(fields[i])
              }
            }
            this.isLoadingAddOrEdit = false
          }
        })
      },
      moveUp (val) {
        console.log(val._id)
        this.$store.dispatch('changeQuesOrder', {id: val._id, operate: 'up'}).then(res => {
          if (res.success) {
            this.refresh()
          }
        })
      },
      moveDown (val) {
        this.$store.dispatch('changeQuesOrder', {id: val._id, operate: 'down'}).then(res => {
          if (res.success) {
            this.refresh()
          }
        })
      },
      moveFirst (val) {
        this.$store.dispatch('changeQuesOrder', {id: val._id, operate: 'top'}).then(res => {
          if (res.success) {
            this.refresh()
          }
        })
      },
      moveLast (val) {
        this.$store.dispatch('changeQuesOrder', {id: val._id, operate: 'bottom'}).then(res => {
          if (res.success) {
            this.refresh()
          }
        })
      },
      deleteQues (val) {
        this.checkIsUsed(deleteQues, true, val._id)
      },
      checkIsUsed (callBack, isDelte, id, confirmInfo) { // 检查模板是否被使用
        this.$store.dispatch('checkTempIsUsed', {temp_id: this.tempId}).then(res => {
          let confirmInfo = this.$t('configLazyLoad.questionnaireConfig.quesTip2')
          if (isDelte) confirmInfo = this.$t('configLazyLoad.questionnaireConfig.quesTip3')
          if (res && res.isUsed) {
            this.$confirm(confirmInfo, this.$t('public.tip'), {
              confirmButtonText: this.$t('public.confirm'),
              cancelButtonText: this.$t('public.cancel'),
              cancelButtonClass: 'primary_btn',
              confirmButtonClass: 'primary_btn',
              type: 'warning'
            }).then(() => {
              if (isDelte) {
                this.$confirm(this.$t('configLazyLoad.questionnaireConfig.quesTip4'), this.$t('public.tip'), {
                  confirmButtonText: this.$t('public.confirm'),
                  cancelButtonText: this.$t('public.cancel'),
                  cancelButtonClass: 'primary_btn',
                  confirmButtonClass: 'primary_btn',
                  type: 'warning'
                }).then(() => {
                  callBack(this, id)
                })
              } else {
                callBack(this)
              }
            }).catch(() => {
              this.$message({
                type: 'info',
                message: this.$t('configLazyLoad.questionnaireConfig.cancelled')
              })
            })
          } else {
            if (isDelte) {
              this.$confirm(this.$t('configLazyLoad.questionnaireConfig.quesTip4'), this.$t('public.tip'), {
                confirmButtonText: this.$t('public.confirm'),
                cancelButtonText: this.$t('public.cancel'),
                cancelButtonClass: 'primary_btn',
                confirmButtonClass: 'primary_btn',
                type: 'warning'
              }).then(() => {
                callBack(this, id)
              })
            } else {
              callBack(this)
            }
          }
        })
      },
      saveQues () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.quesForm.jumpType === 'ansJump') {
//              let flag = true
//              this.quesForm.anws.forEach(item => {
//                if (!item.next) {
//                  flag = false
//                }
//              })
//              if (!flag) {
//                this.$message.error('流向不能为空')
//                return
//              }
              if (this.goNextSelectFlagAns) {
                //  校验跳题 是否是 跳到此题之后的问题
                this.checkIsUsed(addQuestionnaire, false)
              } else {
                this.$message.error(this.$t('configLazyLoad.questionnaireConfig.quesTip6'))
              }
            } else if (this.quesForm.jumpType === 'directJump') {
//              if (!this.quesForm.next) {
//                this.$message.error('流向不能为空')
//                return
//              }
              if (this.goNextSelectFlagDir) {
                //  校验跳题 是否是 跳到此题之后的问题
                this.checkIsUsed(addQuestionnaire, false)
              } else {
                this.$message.error(this.$t('configLazyLoad.questionnaireConfig.quesTip6'))
              }
            } else {
              this.checkIsUsed(addQuestionnaire, false)
            }
          }
        })
      },
      handleAddOrder () { // 新加的问题，order取列表最大的order +1
        let tempOrder = 0
        this.tableData.forEach(item => {
          if (item.order > tempOrder) {
            tempOrder = item.order
          }
        })
        return tempOrder + 1
      }
    },
    activated () {
      this.search()
      let fields = this.$getCache('questionnaireField')
      if (fields) {
        this.quesTmpls = []
        for (let i = 0; i < fields.length; i++) {
          if (fields[i].temp_id === this.tempId) {
            this.quesTmpls.push(fields[i])
          }
        }
      }
    },
    mounted () {
      this.search()
    },
    beforeMount () {
    }
  }
  function addQuestionnaire (self) {
    if (!self.quesForm._id) {
      self.quesForm.order = self.handleAddOrder() || 0
    }
    let anwsArr = []
    self.quesForm.anws.forEach(item => {
      if (item.answer) {
        anwsArr.push(item)
      }
    })
    self.quesForm.anws = anwsArr
    self.$store.dispatch('addQuestionnaireQues', self.quesForm).then(res => {
      if (res.success) {
        self.showRight = false
        self.isLoadingAddOrEdit = false
        self.refresh()
        self.$message.success(self.$t('configLazyLoad.qualityCheck.saveSuccess'))
      }
    })
  }

  function deleteQues (self, id) {
    console.log(id)
    self.$store.dispatch('delTempQues', {_id: id}).then(res => {
      if (res.success) {
        self.showRight = false
        self.isLoadingAddOrEdit = false
        self.$message.success(self.$t('monitor.deleteSuccess'))
        self.refresh()
      }
    })
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .edit_del
    color $c-pink !important
  .delete
    color $c-pink !important
  #questionnaireFieldDAS
    border-bottom: 1px solid #d9d9d9
    border-left: 1px solid #d9d9d9
    border-right: 1px solid #d9d9d9
  .showDetialTitle
    padding: 8px 20px
    font-weight: 600
    font-size: 14px
    border-bottom: 1px solid #ccc
  .el-form
    padding 20px
    .el-input
      font-size 12px
  .searchWrap
    position relative
  .search
    height 30px
    padding 3px 10px
    border-bottom 1px solid $c-border1
    .el-icon-plus,.icon-shuaxin,.icon-fasongchenggong
      color $c-main
      font-size 12px
      margin-right 2px
    .disabled-icon
      color #9D9B9D
    .condition
      width 170px
      margin-right 8px
    .page
      float right
    .icon-text
      margin-right 8px
      cursor pointer
      line-height 30px
  .tips
    color $c-prompt
    font-size 12px
    padding 10px 0px
    a
      margin 0 5px
  .show_answer
    margin-bottom 10px
    line-height: 30px
    .show_answer_label
      width: 100px
      display: inline-block
      float: left
    .show_answer_item
      overflow: hidden
    .el-select
      width 100%
</style>
